package com.zxhhyj.music

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.SystemBarStyle
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Add
import androidx.compose.material.icons.rounded.Pause
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.view.WindowCompat
import com.zxhhyj.music.logic.repository.AndroidMediaLibRepository
import com.zxhhyj.music.logic.repository.SettingRepository
import com.zxhhyj.music.logic.utils.getRealPathFromUri
import com.zxhhyj.music.logic.utils.toSongBean
import com.zxhhyj.music.logic.utils.toTimeString
import com.zxhhyj.music.service.playermanager.MusicPlayer
import com.zxhhyj.music.service.playermanager.PlayerManager
import com.zxhhyj.music.ui.common.AlbumMotionBlur
import com.zxhhyj.music.ui.common.lyric.Lyric
import com.zxhhyj.music.ui.theme.BottomSheetAnimation
import com.zxhhyj.music.ui.theme.StarMusicTheme
import com.zxhhyj.music.ui.theme.isSystemInDarkMode
import com.zxhhyj.music.ui.theme.round
import com.zxhhyj.music.ui.theme.translucentWhiteColor
import com.zxhhyj.ui.theme.LocalColorScheme
import com.zxhhyj.ui.view.AppCard
import com.zxhhyj.ui.view.AppCenterTopBar
import com.zxhhyj.ui.view.RoundColumn
import com.zxhhyj.ui.view.item.Item
import com.zxhhyj.ui.view.item.ItemDivider
import com.zxhhyj.ui.view.item.ItemSlider
import com.zxhhyj.ui.view.item.ItemSpacer
import dev.olshevski.navigation.reimagined.NavBackHandler
import dev.olshevski.navigation.reimagined.material.BottomSheetNavHost
import dev.olshevski.navigation.reimagined.material.BottomSheetProperties
import dev.olshevski.navigation.reimagined.navigate
import dev.olshevski.navigation.reimagined.rememberNavController
import java.io.File

class PreviewSongActivity : ComponentActivity() {

    private val musicPlayer = MusicPlayer(MainApplication.context)

    @SuppressLint("ResourceAsColor")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        WindowCompat.setDecorFitsSystemWindows(window, false)
        PlayerManager.pause()
        setContent {

            with(LocalContext.current as ComponentActivity) {
                if (!isSystemInDarkMode) {
                    enableEdgeToEdge(
                        SystemBarStyle.light(
                            android.R.color.transparent,
                            android.R.color.transparent
                        ),
                        SystemBarStyle.light(
                            android.R.color.transparent,
                            android.R.color.transparent
                        )
                    )
                } else {
                    enableEdgeToEdge(
                        SystemBarStyle.dark(android.R.color.transparent),
                        SystemBarStyle.dark(android.R.color.transparent)
                    )
                }
            }

            StarMusicTheme {
                intent?.data?.let { uri ->
                    val navController = rememberNavController<String>(listOf())
                    NavBackHandler(controller = navController)
                    BottomSheetNavHost(
                        controller = navController,
                        onDismissRequest = {
                            finish()
                        },
                        sheetPropertiesSpec = {
                            BottomSheetProperties(
                                animationSpec = if (SettingRepository.EnableLinkUI) tween(0) else BottomSheetAnimation,
                                skipHalfExpanded = true
                            )
                        }) {
                        val pause by musicPlayer.pauseFlow.collectAsState()
                        val songBean = getRealPathFromUri(
                            LocalContext.current, uri
                        )?.let { path -> File(path).toSongBean() }
                        songBean?.let {
                            musicPlayer.preparePlay(songBean.data)
                        }
                        AppCard(
                            backgroundColor = LocalColorScheme.current.background,
                            shape = RoundedCornerShape(topStart = round, topEnd = round)
                        ) {
                            LazyColumn(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .navigationBarsPadding()
                            ) {
                                item {
                                    AppCenterTopBar(title = {
                                        Text(text = "${songBean?.songName}")
                                    })
                                }
                                item {
                                    val progress by musicPlayer.currentProgressFlow.collectAsState()
                                    val duration by musicPlayer.songDurationFlow.collectAsState()
                                    RoundColumn(modifier = Modifier.fillMaxWidth()) {
                                        Box(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .heightIn(max = 400.dp)
                                        ) {
                                            AlbumMotionBlur(
                                                modifier = Modifier
                                                    .fillMaxSize()
                                                    .background(Color.DarkGray)
                                                    .clipToBounds(),
                                                albumUrl = songBean?.coverUrl,
                                                paused = false
                                            )
                                            Column(modifier = Modifier.fillMaxSize()) {
                                                Lyric(
                                                    modifier = Modifier
                                                        .fillMaxWidth()
                                                        .weight(1.0f),
                                                    lyric = songBean?.lyric,
                                                    liveTime = progress,
                                                    translation = SettingRepository.EnableLyricsTranslation
                                                ) {
                                                    musicPlayer.seekTo(it)
                                                }
                                                CompositionLocalProvider(
                                                    LocalColorScheme provides LocalColorScheme.current.copy(
                                                        highlight = Color.White,
                                                        subText = Color.White,
                                                        disabled = translucentWhiteColor
                                                    )
                                                ) {
                                                    ItemSlider(
                                                        text = { Text(text = progress.toTimeString()) },
                                                        subText = { Text(text = duration.toTimeString()) },
                                                        value = progress.toFloat(),
                                                        valueRange = 0f..duration.toFloat(),
                                                        onValueChange = {
                                                            musicPlayer.seekTo(it.toInt())
                                                        }
                                                    )
                                                }
                                            }
                                        }
                                    }
                                }
                                item {
                                    ItemSpacer()
                                }
                                item {
                                    RoundColumn(modifier = Modifier.fillMaxWidth()) {
                                        Item(
                                            icon = {
                                                Icon(
                                                    imageVector = if (!pause) Icons.Rounded.Pause else Icons.Rounded.PlayArrow,
                                                    contentDescription = null
                                                )
                                            },
                                            text = {
                                                Text(
                                                    text = if (!pause) stringResource(id = R.string.pause) else stringResource(
                                                        id = R.string.play
                                                    )
                                                )
                                            },
                                            subText = {}) {
                                            if (musicPlayer.pauseFlow.value) {
                                                musicPlayer.start()
                                            } else {
                                                musicPlayer.pause()
                                            }
                                        }
                                        ItemDivider()
                                        Item(
                                            icon = {
                                                Icon(
                                                    imageVector = Icons.Rounded.Add,
                                                    contentDescription = null
                                                )
                                            },
                                            text = {
                                                Text(text = stringResource(id = R.string.add_to_media_libs))
                                            },
                                            subText = {},
                                            enabled = SettingRepository.EnableAndroidMediaLibs
                                        ) {
                                            musicPlayer.pause()
                                            AndroidMediaLibRepository.addSong(songBean!!)
                                            startActivity(
                                                Intent(
                                                    this@PreviewSongActivity,
                                                    MainActivity::class.java
                                                )
                                            )
                                            PlayerManager.play(listOf(songBean), 0)
                                            finish()
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (navController.backstack.entries.isEmpty()) {
                        navController.navigate(String())
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        musicPlayer.release()
    }
}